<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\Order;
use plugin\admin\app\model\Shop;
use support\Request;
use support\Response;
use plugin\admin\app\model\Company;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 企业
 */
class CompanyController extends Crud
{

    /**
     * 不需要鉴权的方法
     * @var string[]
     */
    protected $noNeedAuth = ['select'];

    /**
     * @var Company
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Company;
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        if ($format === 'select') {
            return $this->formatSelect($query->get());
        }
        $paginator = $query->paginate($limit);
        $items = $paginator->items();
        foreach ($items as $key => $value) {
            $items[$key]['shop_count'] = Shop::where('company_id', $value['id'])->count();
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $paginator->total(), 'data' => $items]);
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('company/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('company/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('company/update');
    }

}
